package ee.mtiidla.io;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import ee.mtiidla.data.Lenex;

/**
 * Created by Marko on 12.10.2014.
 */
public abstract class FileReader {


	public static File unzipLxfFile(File file) throws IOException {

		if (!file.exists()) {
			throw new IOException(file.getAbsolutePath() + " does not exist.");
		}

		File tmp = File.createTempFile("lenex-", ".zip");
		tmp.deleteOnExit();

		Files.copy(file.toPath(), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);

		try {
			ZipFile lxf = new ZipFile(tmp);

			List<FileHeader> fileHeaders = lxf.getFileHeaders();

			if (fileHeaders.isEmpty()) {
				throw new IOException("Lxf does not contain .lef file");
			}

			FileHeader header = fileHeaders.get(0);
			File lef = new File(tmp.getParent(), header.getFileName());

			lxf.extractFile(header, lef.getParent());

			return lef;

		} catch (ZipException e) {
			throw new IOException(e.getMessage(), e);
		}

	}

	public static Lenex readLenexFile(File file) throws IOException, JAXBException {

		if (file.getName().endsWith(".lxf")) {
			file = unzipLxfFile(file);
		} else if (!file.getName().endsWith(".lef")) {
			throw new IOException("Invalid input file, must be .lxf or .lef");
		}

		JAXBContext jc = JAXBContext.newInstance(Lenex.class);
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		return (Lenex) unmarshaller.unmarshal(file);

	}

	public static String readTemplateFile(File template) throws IOException {

		if (template == null) {
			throw new IOException("Template file not selected");
		}

		BufferedReader br = new BufferedReader(new java.io.FileReader(template));
		try {
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();

			while (line != null) {
				sb.append(line);
				sb.append(System.lineSeparator());
				line = br.readLine();
			}
			return sb.toString();
		} finally {
			br.close();
		}
	}

}
